package com.baide.sanguanheyi.ct;

import com.baide.sanguanheyi.config.ThreadManager;
import com.baide.sanguanheyi.interfaces.CtCallBack;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@ChannelHandler.Sharable
public class HeartBeatClientHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    XmlUtils utils;
    CtCallBack ctCallBack;

    public void setCtCallBack(CtCallBack ctCallBack) {
        this.ctCallBack = ctCallBack;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("ct 连接成功");
        if (ctCallBack != null) ctCallBack.ctConnectSuccess();
        ctx.fireChannelActive();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("ct 连接停止");
        if (ctCallBack != null) ctCallBack.ctConnectOff();
    }

    static StringBuffer sb = new StringBuffer();//占包处理
    final String head = "NTCTTP/1.0";
    final String end = "</Envelope>";

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String message = (String) msg;
//        System.out.println(message);
        sb.append(message.trim());
//        System.out.println(sb.toString());
        synchronized (this) {
            if (!sb.toString().startsWith(head) && sb.toString().contains(head)) {
                sb.delete(0, sb.indexOf(head));
            }
            while (sb.toString().startsWith(head) && sb.length() > 0 && sb.indexOf(end) > 0) {
                releaseMsg(sb.substring(0, sb.indexOf(end) + end.length()));
                sb.delete(0, sb.indexOf(end) + end.length());
            }
        }
    }

    private void releaseMsg(String message) {
        if (message.contains("ctConclusionResult")) {
            Map<String, Object> map = utils.getString(message);
            Map<String, Object> body = (Map<String, Object>) map.get("Body");
            ThreadManager.getThreadPollProxy().execute(new Runnable() {
                @Override
                public void run() {
                    ctCallBack.ctResult(body);
                }
            });
        }
//        System.out.println("releaseMsg:----------"+message+"-----------");
//        Map<String, Object> map = utils.getString(message);
//        Map<String, Object> header = (Map<String, Object>) map.get("Header");
//        Map<String, Object> body = (Map<String, Object>) map.get("Body");
//        switch (header.get("MessageName").toString()) {
//            case "ctHeartBeatResponse"://心跳
//                break;
//            case "ctImageMessage"://获取到图片信息
//                String prn = body.get("Prn").toString();//图片流水号
//                String barcode = body.get("Barcode").toString();//条码
//                String billNo = body.get("BillNo").toString();//总运单号
//                int length = Integer.parseInt(body.get("Length").toString());//包裹长度
//                boolean forceSplit = Boolean.parseBoolean(body.get("ForceSplit").toString());//是否强制分图
//                break;
//            case "ctConclusionResult":
//                String barcode1 = body.get("Barcode").toString();//条码
//                String billNo1 = body.get("BillNo").toString();//总运单号
//                String prn1 = body.get("PRN").toString();//图像流水
//                String judgeResult = body.get("JudgeResult").toString();//安检判读结果 R-可疑，C-安全，N-未判图，O-超时，F-系统错误
//                int judgeCategory = Integer.parseInt(body.get("JudgeCategory").toString());//判读类别 0- 不分类、 1- 一类物品、2- 二类物品、3- 三类物品
//                /**
//                 * 结论掩码
//                 * 按位标识结论中嫌疑的原因
//                 * Bit0：人工嫌疑
//                 * Bit1：AI 嫌疑
//                 * Bit4：预审布控
//                 * Bit5：随机布控
//                 * Bit8：图单不符
//                 */
//                int resultMask = Integer.parseInt(body.get("ResultMask").toString());//
//                String userId = body.get("UserId").toString();//判图员 ID
//                int department = Integer.parseInt(body.get("Department").toString());//判图员 ID
//                String judgeTime = body.get("JudgeTime").toString();//判图时间
//                new Thread() {
//                    @Override
//                    public void run() {
//                        if (judgeResult.equals("C")) {
//                            ctCallBack.ctResult(true, body);
//                        } else {
//                            ctCallBack.ctResult(false, body);
//                        }
//                    }
//                }.start();
//                break;
//            case "ctDeviceStatus"://ct状态
//                /**
//                 * 0 初始化；1 就绪；2 故障；3
//                 * 诊断中；4 关机（离线）5；待
//                 * 机；6 急停；7 扫描；8 直通；
//                 * 9 暂停；10 维护
//                 */
//                int status = Integer.parseInt(body.get("Status").toString());
//                break;
//            case "ctSortingResult":
//                boolean result = (boolean) body.get("Result");//1, 被分拣，0，没有分拣。
//                String billNo2 = body.get("BillNo").toString();
//                String barcode2 = body.get("Barcode").toString();
//                break;
//        }
    }


}